package business.facade;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import entities.CandidatoEntity;
import entities.FormElementEntity;
import entities.GestioneCandidatoEntity;

import util.DynamicObjectHandler;
import util.ServerResponse;
import util.SessionFactorySingleton;

import business.bl.BasicOperation;
import business.dto.CandidatoDTO;
import business.dto.GestioneCandidatoDTO;

public class GestioneCandidatoFacade implements BasicOperation{
	public static Logger logger = LogManager.getLogger(GestioneCandidatoFacade.class);

	@Override
	public ServerResponse save(HashMap parametersList) throws Exception {
		logger.info("BEGIN - GestioneCandidatoFacade - save");
		String servletName = (String) parametersList.get("servletName");
	     
        String serverResponseMessage="OK";
        ServerResponse returnValue = new ServerResponse(servletName, null, serverResponseMessage);
        
        HttpServletRequest request=(HttpServletRequest)parametersList.get("request");
                
        String name = request.getParameter("name");
        
       
        String id= request.getParameter("id");
       

        Map parameterMap = request.getParameterMap();
        Set keySet = parameterMap.keySet();
        
        Iterator it = keySet.iterator();
        
        HashMap<String, String> gestioneCandidatoParameter=new HashMap<String, String>();
        
//      StringBuffer customFields=new StringBuffer();
	      while (it.hasNext())
	      {
	          String key = (String) it.next();
	          String value = (String) request.getParameter(key);
	          logger.debug(value);
	          gestioneCandidatoParameter.put(key, value);
	      }
        
        
//         name=(parameterMap.get("name")).toString();
        
        
//	    String method = request.getParameter("method");   
        
        
        try {
        	SessionFactory sessionFactory = SessionFactorySingleton.getInstance().getSesssionFactory();
		    logger.info("istanziato il session factory");
		    
		    DynamicObjectHandler doh=new DynamicObjectHandler();
		    
		    
		    
		    
		    Session session = sessionFactory.openSession();
		    
		    GestioneCandidatoEntity gce=new GestioneCandidatoEntity();
		    GestioneCandidatoDTO gcDTO=new GestioneCandidatoDTO();

		    doh.fill(gcDTO, gestioneCandidatoParameter);
		    
		    //	BEGIN - PULITURA PER BUG SU TEXT AREA
		    
//		    gcDTO.setSchedaCandidato(gcDTO.getSchedaCandidato().trim());
//		    gcDTO.setSchedaCliente(gcDTO.getSchedaCliente().trim());
//		    gcDTO.setClienteFinale(gcDTO.getClienteFinale().trim());
		   
		    
//			END - PULITURA PER BUG SU TEXT AREA
		    
	    	GestioneCandidatoEntity fromDb = (GestioneCandidatoEntity) session.createCriteria(GestioneCandidatoEntity.class)
		    	.add(Restrictions.eq( "id", new Integer(id))).uniqueResult();
		    
				   	
	    	if(fromDb!=null){
	    		gce=fromDb;
	    		doh.update(gce, gcDTO);
	    	}else{
	    		doh.update(gce, gcDTO);
	    	}
			
	    	
	    	
			gce.setId(new Integer(id));
			
			
			try {
				
				Date d=new Date();
	    		
				ResourceBundle rb= ResourceBundle.getBundle("bundle");
				String dateFormat=rb.getString("DATE_FORMAT");
				
	    		SimpleDateFormat sdf=new SimpleDateFormat(dateFormat);
				
				String scadenzaContratto=gestioneCandidatoParameter.get("scadenzaContratto");
				if(scadenzaContratto!=null){
					
		    		d=sdf.parse(scadenzaContratto);
			    	
			    	gce.setScadenzaContratto(d);
				}else{
					gce.setScadenzaContratto(null);
				}
				
				
		    	
		    	
		    	String dataColloquio=gestioneCandidatoParameter.get("dataColloquio");
				if(dataColloquio!=null){
					d=sdf.parse(dataColloquio);
			    	gce.setDataColloquio(d);
				}else{
					gce.setDataColloquio(null);
				}
		    	
		    	
			} catch (java.text.ParseException e) {
				logger.error(e); 
			}
    		
			
			CandidatoEntity ce=new CandidatoEntity();
			
			
			
			
		    Transaction transaction = session.beginTransaction();
	    	session.merge(gce);
	    
	    	transaction.commit();
		    session.flush();
		   
		   	session.close();
		   	
		   	returnValue.setResponseMessage("Dati Pannello salvato correttamente");
		   	
		   	
		    
		} catch (Throwable ex) {
		    // Log the exception.
		    logger.error("Initial SessionFactory creation failed.", ex); 
		    returnValue.setResponseMessage("KO");
			returnValue.setResponseMessage("Salvataggio dei dati pannello fallito");
		}
        
		logger.info("END - GestioneCandidatoFacade - save");
        return returnValue;
	}

	@Override
	public ServerResponse list(HashMap parametersList) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ServerResponse delete(HashMap parametersList) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ServerResponse load(HashMap parametersList) throws Exception {
		logger.info("BEGIN - GestioneCandidatoFacade - load");
		String servletName = (String) parametersList.get("servletName");
	     

        String serverResponseMessage="OK";
        ServerResponse returnValue = new ServerResponse(servletName, null, serverResponseMessage);
        
        HttpServletRequest request=(HttpServletRequest)parametersList.get("request");
                
        String id = request.getParameter("id");
       
        logger.debug(id);
        
        try {
        	SessionFactory sessionFactory = SessionFactorySingleton.getInstance().getSesssionFactory();
		    logger.info("istanziato il session factory");
		    
		    GestioneCandidatoDTO gcDTO= new GestioneCandidatoDTO();
		    
		    GestioneCandidatoEntity fromDb =null;
		    
		    
		    
		    Session session = sessionFactory.openSession();
		    if(!id.equals("null")){
		    	fromDb = (GestioneCandidatoEntity) session.createCriteria(GestioneCandidatoEntity.class)
		    	    	.add(Restrictions.eq( "id", new Integer(id))).uniqueResult();
		    	
		    }
		    
		    session.flush();
		    
		    
		    if(fromDb!=null){
		    	gcDTO=fromDb.getDTO();
		    }
//		    else{
		    	if(!id.equals("null")){
			    	gcDTO.setId(new Integer(id));
			    }
//		    } 
		    	
		    		    
		    returnValue.addData(gcDTO);
		   
//		   		CandidatoDTO ceDTO=fromDb.get(i).getDTO();
//		   		ceDTO.setSkill(feeSkill.getDTO().toString(ceDTO.getSkill()));
//		   		ceDTO.setAmbientiSvil(feeAmbientiSvil.getDTO().toString(ceDTO.getAmbientiSvil()));
//		   		ceDTO.setSistemiOperativi(feeSistemiOperativi.getDTO().toString(ceDTO.getSistemiOperativi()));
//		   		ceDTO.setDb(feeDB.getDTO().toString(ceDTO.getDb()));
//		   		ceDTO.setAppServer(feeAppServer.getDTO().toString(ceDTO.getAppServer()));
//		   		ceDTO.setProdotti(feeProdotti.getDTO().toString(ceDTO.getProdotti()));	
//		   		ceDTO.setLingue(feeLingue.getDTO().toString(ceDTO.getLingue()));
//		   		ceDTO.setPatente(feePatente.getDTO().toString(ceDTO.getPatente()));
//		   		ceDTO.setComeCiHaiConosciuto(feeCCHC.getDTO().toString(ceDTO.getComeCiHaiConosciuto()));
//		   		
//		   		
//			
		   	
		   	
		    
		} catch (Throwable ex) {
		    // Log the exception.
		    logger.error("Initial SessionFactory creation failed.", ex); 
		    returnValue.setResponseMessage("KO");
			returnValue.setResponseMessage("Caricamento del Pannello fallito");
		}
        
		logger.info("END - GestioneCandidatoFacade - load");
		
        return returnValue;
        
        	
	}

	@Override
	public ServerResponse upload(HashMap parametersList) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ServerResponse create(HashMap parametersList) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
}
